//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package org_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/org_member_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type InviteInfoDbItem struct {
	InviteCode   string `bson:"_id"`
	OrgId        string `bson:"orgId"`
	CreateUserId string `bson:"createUserId"`
	CreateTime   int64  `bson:"createTime"`
	ExpireTime   int64  `bson:"expireTime"`
}

func (item *InviteInfoDbItem) ToInviteInfo() *org_member_api.InviteInfo {
	return &org_member_api.InviteInfo{
		InviteCode:   item.InviteCode,
		CreateUserId: item.CreateUserId,
		CreateTime:   item.CreateTime,
		ExpireTime:   item.ExpireTime,
	}
}

type _InviteDao struct {
	mc *mongo.Collection
}

func newInviteDao(db *mongo.Database) (*_InviteDao, error) {
	mc := db.Collection(db_ns.DB_NS_ORG + "invite")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"orgId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_InviteDao{mc: mc}, nil
}

func (db *_InviteDao) Insert(ctx context.Context, dbItem *InviteInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_InviteDao) Get(ctx context.Context, inviteCode string) (*InviteInfoDbItem, error) {
	retItem := &InviteInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": inviteCode}).Decode(retItem)
	return retItem, err
}

func (db *_InviteDao) Exist(ctx context.Context, orgId, inviteCode string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"orgId": orgId, "_id": inviteCode})
	return count > 0, err
}

func (db *_InviteDao) RemoveExpire(ctx context.Context, orgId string, nowTime int64) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"orgId": orgId, "expireTime": bson.M{"$lt": nowTime}})
	return err
}

func (db *_InviteDao) Remove(ctx context.Context, orgId, inviteCode string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": inviteCode, "orgId": orgId})
	return err
}

func (db *_InviteDao) RemoveByOrg(ctx context.Context, orgId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"orgId": orgId})
	return err
}

func (db *_InviteDao) Count(ctx context.Context, orgId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"orgId": orgId})
	return uint32(count), err
}

func (db *_InviteDao) List(ctx context.Context, orgId string, offset, limit int64) ([]*InviteInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"orgId": orgId}, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"createTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*InviteInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
